//封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'
import {mergeCartAPI} from '@/apis/cart'
export const useCartStore = defineStore(
  'cart',
  () => {
    //1.定义购物车数据
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //2.定义action
    const updateNewCartList = async () => {
      const res = await findNewCartListAPI()
      // 确保返回的数据是数组
      cartList.value = Array.isArray(res.result) ? res.result : []
    }
    //添加商品到购物车
    const addCart = async (goods) => {
      //已经添加过，count+1

      const { skuId, count } = goods
      if (isLogin.value) {
        //如果登录了，添加到购物车,走接口
        try {
          await insertCartAPI({ skuId, count })
          updateNewCartList()
        } catch (error) {
          console.error('添加购物车失败:', error)
        }
      } else {
        //没有添加过，添加到购物车
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }

    // 删除购物车
    const delCart = async (skuId) => {
      if (isLogin.value) {
        // 调用接口实现接口购物车中的删除功能
        try {
          await delCartAPI([skuId])
          updateNewCartList()
        } catch (error) {
          console.error('删除购物车失败:', error)
        }
      } else {
        // 思路：
        // 1. 找到要删除项的下标值 - splice
        // 2. 使用数组的过滤方法 - filter
        const idx = cartList.value.findIndex((item) => skuId === item.skuId)
        cartList.value.splice(idx, 1)
      }
    }

    //单选功能
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      if (item) {
        item.selected = selected
      }
    }
    //计算属性
    // 1. 总的数量 所有项的count之和
    const allCount = computed(() =>
      Array.isArray(cartList.value) ? cartList.value.reduce((a, c) => a + c.count, 0) : 0
    )
    // 2. 总价 所有项的count*price之和
    const allPrice = computed(() =>
      Array.isArray(cartList.value) ? cartList.value.reduce((a, c) => a + c.count * c.price, 0) : 0
    )
    // 3. 已选择数量
    const selectedCount = computed(() => {
      if (!Array.isArray(cartList.value)) return 0
      return cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0)
    })
    // 4. 已选择商品价钱合计
    const selectedPrice = computed(() => {
      if (!Array.isArray(cartList.value)) return 0
      return cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    })

    // 全选功能action
    const allCheck = (selected) => {
      // 把cartList中的每一项的selected都设置为当前的全选框状态
      if (Array.isArray(cartList.value)) {
        cartList.value.forEach((item) => (item.selected = selected))
      }
    }

    // 是否全选计算属性
    const isAll = computed(() =>
      Array.isArray(cartList.value) && cartList.value.length > 0
        ? cartList.value.every((item) => item.selected)
        : false
    )

    //清除购物车
    const clearCart = () => {
      cartList.value = []
    }

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      allCheck,
      isAll,
      selectedCount,
      selectedPrice,
      clearCart,
      updateNewCartList
    }
  },
  {
    persist: true
  }
)
